package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;

    /**
     * 得到日期列表，方便查询
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDatalist(LocalDate begin, LocalDate end){
        List<LocalDate> Datelist = new ArrayList<>();
        Datelist.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            Datelist.add(begin);
        }
        return Datelist;
    }
    //TODO 有优化的空间，这里连续查了end-begin+1次数据库（批量查询）
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end){
        //获取begin至end的所有日期
        List<LocalDate> Datelist = getDatalist(begin,end);
        StringBuilder data_list = new StringBuilder();
        StringBuilder amout_list = new StringBuilder();
        Integer size = Datelist.size();
        //获取每个日期对应的营业额（订单状态为已完成且时间落在每个日期里）
        for(int k=0;k<size;k++){
            LocalDate date = Datelist.get(k);
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            BigDecimal temp = reportMapper.getAmount(begintime,endtime);
            BigDecimal amount = (temp==null?new BigDecimal(0.0):temp);
            if(k!=size-1)
            {
                data_list.append(date + ",");
                amout_list.append(amount + ",");
            }
            else{
                data_list.append(date);
                amout_list.append(amount);
            }
        }
        //封装vo结果，返回
        String dataresult = data_list.toString();
        String amoutresult = amout_list.toString();
        log.info("最终的data列表：{}",dataresult);
        log.info("最终的amount列表：{}",amoutresult);
        return TurnoverReportVO.builder()
                .dateList(dataresult)
                .turnoverList(amoutresult)
                .build();
    }

    /**
     * 根据传入的时间段查询每天的新增用户数和每日之前的总用户数，封装成返回UserReportVO对象返回
     * @param begin
     * @param end
     * @return
     */
    //TODO 在sql查询有优化的空间
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end){
        //获取日期列表
        List<LocalDate> Datelist = getDatalist(begin,end);
        StringBuilder data_list = new StringBuilder();
        StringBuilder data_user_list = new StringBuilder();
        StringBuilder total_user_list = new StringBuilder();
        int size= Datelist.size();
        Integer totaluser = 0 ;
        //获取每日新增用户数
        //获取每日之前的总用户数
        for(int k=0;k<size;k++){
            LocalDate date = Datelist.get(k);
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Integer temp = reportMapper.getUseramount(begintime,endtime);
            Integer amount = (temp==null?0:temp);
            totaluser += amount;
            if(k!=size-1)
            {
                data_list.append(date + ",");
                data_user_list.append(amount + ",");
                total_user_list.append(totaluser + ",");
            }
            else{
                data_list.append(date);
                data_user_list.append(amount);
                total_user_list.append(totaluser);
            }
        }
        String dataList = data_list.toString();
        String newuserlist = data_user_list.toString();
        String totallist = total_user_list.toString();
        //封装结果返回
        return UserReportVO
                .builder()
                .dateList(dataList)
                .newUserList(newuserlist)
                .totalUserList(totallist)
                .build();
    }

    /**
     * 获得时间段内销量排名前10的的商品及其数量
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end){
        StringBuilder namelist = new StringBuilder();
        StringBuilder numberlist = new StringBuilder();
        //获取时间段内top10的商品名称和数量
        List<GoodsSalesDTO> list = reportMapper.getTOP_sales(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        int size = list.size();
        log.info("SIZE:{}",size);
        //分离处理
        for(int k=0;k<size;k++){
            GoodsSalesDTO obj = list.get(k);
            log.info("第一个商品名：{}",obj.getName());
            log.info("第一个商品的销量：{}",obj.getNumber());
            if(k!=size-1){
                namelist.append(obj.getName() + ",");
                numberlist.append(obj.getNumber() + ",");
            }
            else{
                namelist.append(obj.getName());
                numberlist.append(obj.getNumber());
            }
        }
        //封装结果
        return SalesTop10ReportVO.builder()
                .nameList(namelist.toString())
                .numberList(numberlist.toString())
                .build();
    }
}
